import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'dart:io';

import 'package:bot_toast/bot_toast.dart';
import 'package:exams_app/examslive_module/examslive2_page.dart';
import 'package:exams_app/gen_a/A.dart';
import 'package:exams_app/home_module/myprofile_module/myprofile_page.dart';

import 'package:exams_app/home_module/exams_module/test_instructions_page.dart';
import 'package:exams_app/login_module/logic.dart';
import 'package:exams_app/login_module/real_name_authen/view.dart';
import 'package:exams_app/login_module/view.dart';
import 'package:exams_app/message_module/view.dart';
import 'package:exams_app/net/Address.dart';
import 'package:exams_app/net/DioManager.dart';
import 'package:exams_app/net/persisten_storage.dart';
import 'package:exams_app/widget/hexcolor.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ios_screenshots/flutter_ios_screenshots.dart';
import 'package:flutter_swipe_action_cell/core/cell.dart';
import 'package:get/get.dart';
import 'package:rtmp_publisher/camera.dart';

import '../live_module/live_pages.dart';
// import '../live_page.dart';
// import '../logic.dart';

import 'package:exams_app/home_module/exams_module/logic.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import '../account_set_module/account_seting_page.dart';

import 'package:flutter_svg/svg.dart';
import 'package:exams_app/widget/webview_page.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:exams_app/login_module/real_name_authen/renzhen_info_page.dart';
import '../myprofile_module/myprofile_logic.dart';
import '../myexams_module/myexams_pages.dart';
import '../help_module/help_pages.dart';
import '../account_set_module/account_logic.dart';
import 'device_page.dart';
import 'package:exams_app/examslive_module/examslive_page.dart';
import 'package:url_launcher/url_launcher.dart';

class HomeModulePage extends StatefulWidget {
  @override
  _HomeModulePageState createState() => _HomeModulePageState();
}

class _HomeModulePageState extends State<HomeModulePage> {

  final HomeModuleLogic logic = Get.put(HomeModuleLogic());
  final AccountLogic accountLogicClogic = Get.put(AccountLogic());


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // _esController = EasyRefreshController();

    requestDataWithDocuments();

    _listeningIosEndScreenshots();

    // controller = CameraController(cameras[1], ResolutionPreset.medium);
    //
    // controller.initialize().then((_) {
    //   if (!mounted) {
    //
    //     return;
    //   }
    //   setState(() {});
    // });


    requestPermiss();


    // logic.requestDataWithXuzhi();
    // accountLogicClogic.requestDataWithUser();
    // accountLogicClogic.requestDataWithUserInfo();
  }


  requestPermiss() async {
    //请求权限
    Map<PermissionGroup, PermissionStatus> permissions =
    await PermissionHandler()
        .requestPermissions([PermissionGroup.camera,
      PermissionGroup.microphone,PermissionGroup.photos,PermissionGroup.mediaLibrary]);

    //校验权限
    if(permissions[PermissionGroup.camera] != PermissionStatus.granted){
      print("无照相权限");
    }
    setState(() {

    });
  }

  ///监测截屏
  void _listeningIosEndScreenshots() {
    FlutterIosScreenshots.listeningPlatform((Uint8List endResult) {
      // _image = true;
      // _image8List = endResult;

      print('+++++++++++++++++++++++++++++++++ 监听到iOS 截屏了');


      setState(() {});
    });
  }

  var page = 0;
  List dataList;
  EasyRefreshController _esController = EasyRefreshController();

  var max_num;
  bool isnumopen;

  /// 学习资料
  void requestDataWithDocuments() async {
    var params = {'page': page, 'limit': 10, 'folder_id': 0};

    String result =
        await DioUtils(url: await PersistentStorage().getStorage('urlStr'))
            .postModel(Address.getattt,
                model: 'documents.document',
                function_name: '_api_page',
                params: params);
    Map json = jsonDecode(result);
    DocumentModel model = DocumentModel.fromJson(json);
    if (page == 0) {
      dataList = List();
      _esController.resetLoadState();
      dataList.clear();
      dataList.addAll(model.data);
    } else {
      if (json['data'].length > 0) {
        // for(int i = 0;i<model.data.length;i++){
        //   model.data[i].isSelect = false;
        // }

        dataList.addAll(model.data);
      } else if (json['data'].length - 1 <= 0) {
        _esController.finishLoad(success: true, noMore: true);
        // _esController.finishLoad(success: true, noMore: true);
        // COToast.show('暂无更多',a: ToastGravity.BOTTOM);
        // Toast.toast(context,msg: '暂无更多',position:ToastPostion.bottom);
        BotToast.showText(text: '暂无更多');
      }
    }

    setState(() {});
  }

  /// 获取最大直播人数


  @override
  Widget build(BuildContext context) {

    if (dataList == null) {
      return Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      );
    }

    return GetBuilder<HomeModuleLogic>(

      // init: HomeModuleLogic(),
      initState: (sz) {
        // accountLogicClogic.requestDataWithUserInfo();
        accountLogicClogic.requestDataWithUser();

      },
      builder: (_homelogic) {
        return Scaffold(
          appBar: AppBar(
              title: Text('首页'),
              centerTitle: true,
              actions: [
                IconButton(
                    icon: Image.asset(A.assets_top_msg),
                    onPressed: () {
                      // Get.to(CameraExampleHome());
                      Get.to(MessageModulePage());
                    })
              ],
              //设置前面显示图片
              leadingWidth: 222,
              leading: Builder(
                builder: (BuildContext context) {
                  return GestureDetector(
                    onTap: () {
                      Scaffold.of(context).openDrawer();
                    },
                    child: Container(
                      color: Colors.transparent,
                      margin: EdgeInsets.only(left: 15),
                      child: GetBuilder<AccountLogic>(
                        init: AccountLogic(),
                        builder: (_acclogic) {
                          return Row(
                            children: [

                              _acclogic.imageHeader.value==''?
                              ClipOval(
                                child: Image.network(
                                  _acclogic.userJson['data'][0]
                                      ['image_128'],
                                  fit: BoxFit.cover,
                                  width: 25,
                                  height: 25,
                                ),
                              ):ClipOval(
                                child: Image.file(File(_acclogic.imageHeader.value),fit: BoxFit.cover,
                                  width: 25,
                                  height: 25,),
                              ),
                              Container(

                                margin: EdgeInsets.only(left: 5),
                                width: 60,
                                child: Text(
                                  _acclogic.userJson['data'][0]
                                      ['name'],
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ],
                          );
                        },
                      ),
                    ),
                  );
                },
              )),
          drawer: Container(
            width: Get.width / 2,
            child: drawerWidget0(),
          ),
          body: EasyRefresh.custom(
            firstRefresh: true,
            controller: _esController,
            header: MaterialHeader(),
            footer: MaterialFooter(),
            onLoad: () async {
              page++;
              requestDataWithDocuments();
              await Future.delayed(Duration(milliseconds: 250), () {});
            },
            onRefresh: () async {
              page = 0;
              requestDataWithDocuments();
              _homelogic.requestDataWithXuzhi();

              accountLogicClogic.requestDataWithUser();

            },
            slivers: [
              SliverToBoxAdapter(
                  child: Visibility(
                      visible: logic.haveLive.value,
                      child: GestureDetector(
                        onTap: () {
                            Get.to(LivePages(logic.appHomeJson['data']['live_id']));
                        },
                        child: Container(
                          margin: EdgeInsets.only(left: 0, right: 0),
                          // padding: EdgeInsets.only(left: 15,right: 15),
                          // height: 200,
                          color: Colors.white,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              GestureDetector(
                                onTap: () {
                                  // Get.to(LivePages());


                                  Get.to(LivePages(logic.appHomeJson['data']['live_id']));

                                },
                                child: Container(
                                  margin: EdgeInsets.only(left: 15, top: 10),
                                  child: Text(
                                    '直播培训',
                                    style: TextStyle(
                                        fontSize: 16,
                                        color: HexColor('#333333'),
                                        fontWeight: FontWeight.w500),
                                  ),
                                ),
                              ),
                              Container(
                                margin: EdgeInsets.only(top: 15, bottom: 15),
                                width: Get.width,
                                color: Colors.white,
                                // child: Text(''),
                                // child: Image.asset(
                                //   A.assets_z1,
                                //   height: 180,
                                //   fit: BoxFit.cover,
                                // ),
                                child: Image.network('${logic.appHomeJson['data']['live_image_128']}',height: 180,fit: BoxFit.cover,),
                              ),
                              Container(
                                padding: EdgeInsets.only(left: 15,right: 15),
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      children: [
                                        ClipOval(
                                          child: Image.network(
                                            logic.appHomeJson['data']
                                                ['live_user_image_128'],
                                            fit: BoxFit.cover,
                                            width: 25,
                                            height: 25,
                                          ),
                                        ),
                                        SizedBox(
                                          width: 10,
                                        ),
                                        Text(
                                            '${logic.appHomeJson['data']['live_user_id_name']}'),
                                      ],
                                    ),
                                    Image.asset(A.assets_playerlive)
                                  ],
                                ),
                                margin: EdgeInsets.only(bottom: 5),
                              )
                            ],
                          ),
                        ),
                      ))),
              SliverToBoxAdapter(
                child: Visibility(
                  visible: logic.haveExams.value,
                  child: Container(
                    alignment: Alignment.center,
                    child: Stack(
                      children: [
                        Align(
                          alignment: Alignment.bottomRight,
                          child: Container(
                            alignment: Alignment.center,
                            child: Text(
                              '为了您能顺利完成考试,请仔细阅读<考试须知>',
                              style: TextStyle(
                                  fontSize: 12, color: HexColor('#D89100')),
                            ),
                            height: 25,
                            width: Get.width,
                            decoration: BoxDecoration(
                              color: HexColor('#FFE3AA'),
                              borderRadius: BorderRadius.vertical(
                                bottom: Radius.circular(8),
                              ),
                            ),
                          ),
                        ),
                        Align(
                          // alignment: Alignment.center,
                          child: Column(
                            // mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Container(
                                margin: EdgeInsets.only(top: 15),
                                child: Text(
                                  '${logic.stateKS}',
                                  style: TextStyle(
                                      fontSize: 14, color: HexColor('#999999')),
                                ),
                              ),

                              CountTextWidget(
                                  logic.appHomeJson['data']['exam_seconds']),

                              // Container(
                              //   margin: EdgeInsets.only(top: 15),
                              //   alignment: Alignment.center,
                              //   // color: Colors.red,
                              //   child: Text(
                              //     ('${logic
                              //         .appHomeJson['data']['exam_date_start']}'),
                              //     style: TextStyle(
                              //         fontSize: 22,
                              //         color: HexColor('#333333'),
                              //         fontWeight: FontWeight.w500),
                              //   ),
                              // )
                            ],
                          ),
                        )
                      ],
                    ),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(8.0),
                        boxShadow: [
                          BoxShadow(
                              color: Colors.black12,
                              offset: Offset(0.0, 3.0), //阴影xy轴偏移量
                              blurRadius: 2.0, //阴影模糊程度
                              spreadRadius: 1.0 //阴影扩散程度
                              )
                        ]),
                    margin: EdgeInsets.only(left: 15, right: 15, top: 15),
                    height: 120,
                  ),
                ),
              ),
              SliverToBoxAdapter(
                  child: GestureDetector(
                child: Container(
                    width: Get.width,
                    // height: 100,
                    padding: EdgeInsets.only(left: 10, right: 10, top: 10),
                    child: Flex(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      direction: Axis.horizontal,
                      children: [
                        Expanded(
                          child: GestureDetector(
                            child: Container(
                              // margin: EdgeInsets.only(right: 5),
                              padding: EdgeInsets.all(5),
                              child: Image.asset(
                                A.assets_ksxz,
                                fit: BoxFit.contain,
                              ),
                            ),
                            onTap: () {
                              // if(logic.appHomeJson['data']['exam_id']==''){
                              //   BotToast.showText(text: '考试暂未开始');
                              //   return;
                              // }
                              Get.to(TextInstructionsPage('no'));
                            },
                          ),
                        ),
                        Expanded(
                          child: GestureDetector(
                            child: Container(
                              padding: EdgeInsets.all(5),
                              child: Image.asset(
                                A.assets_sbjc,
                                fit: BoxFit.contain,
                              ),
                            ),
                            onTap: () {
                              // Get.to(DeviceTestPage());
                              // requestPermission();
                              Get.to(DevicePage());

                              print('设备检测');
                            },
                          ),
                        ),
                      ],
                    )),
              )),
              SliverToBoxAdapter(
                child: Container(
                  height: 11,
                  color: HexColor('#F9F9F9'),
                ),
              ),
              SliverToBoxAdapter(
                  child: Container(
                margin: EdgeInsets.only(left: 15),
                child: Text(
                  '学习资料',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
                ),
              )),
              SliverToBoxAdapter(
                child: Container(
                  margin: EdgeInsets.only(top: 15, left: 15, right: 15),
                  color: HexColor('#EEEEEE'),
                  height: 1,
                ),
              ),
              SliverList(
                  delegate: SliverChildBuilderDelegate(_buildListItem,
                      childCount: dataList.length)),
            ],
          ),
        );
      },
    );
  }



  MyProfileLogic profileLogic = Get.put(MyProfileLogic());

  Widget _buildListItem(BuildContext context, int index) {
    Data model = dataList[index];

    return
      SwipeActionCell(
      key: ValueKey(dataList[index]),
      performsFirstActionWithFullSwipe: false,
      trailingActions: <SwipeAction>[
        SwipeAction(
          title: '收藏',
          color: Theme.of(context).primaryColor,
          widthSpace: 100,
          onTap: (CompletionHandler handler) async {
            handler(false);
            profileLogic.requestDataWithFouce(
                '${await PersistentStorage().getStorage('uid')}',model.id);
            // logic.requestDataWithCollection('${await PersistentStorage().getStorage('uid')}');
          },
        ),
      ],
      child: GestureDetector(
        child: Container(
          color: Colors.transparent,
          margin: EdgeInsets.all(0),
          child: Row(
            // crossAxisAlignment:CrossAxisAlignment.start,
            children: [
              Container(
                margin: EdgeInsets.only(left: 15),
                child: SvgPicture.network(model.icon),
              ),
              Container(
                // color: Colors.red,
                width: Get.width-20 ,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      width: Get.width-100,
                      margin: EdgeInsets.only(top: 15, right: 0, left: 5),
                      child: Text(
                        '${model.name}',
                        style:
                            TextStyle(fontSize: 16, color: HexColor('#333333')),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 0, left: 5),
                      child: Text(
                        '上传于${model.pastTime}',
                        style:
                            TextStyle(fontSize: 12, color: HexColor('#999999')),
                      ),
                    ),
                    // Text('2020年最新出台政策.pdf',style: TextStyle(fontSize: 12,color: HexColor('#999999')),),
                    Container(
                      margin: EdgeInsets.only(top: 15,right: 5),
                      color: HexColor('#EEEEEE'),
                      width: Get.width,
                      height: 1,
                      child: Text(''),
                    )
                  ],
                ),
              )
            ],
          ),
        ),
        onTap: ()async {
          if (model.type == '文件夹') {
            // Get.to(DocumentJiaListPage(model.id,model.name,domain: '[]',));
          } else {
            // Get.to(MyWebView(url: model.previewUrl, title: '预览'));
            // await launch(url);
            String url = '${model.download_url}';
            if(await canLaunch(url)){
              await launch(url);
            }
            else{
              BotToast.showText(text: 'url不能进行访问');
              throw 'url不能进行访问，异常。';
            }

          }
        },
      ),
    );
  }

  Widget drawerWidget0(){
    return Container(
      color: Colors.white,
      child: ListView(
        children: [
          Container(
              margin: EdgeInsets.only(top: 20, bottom: 0),
              alignment: Alignment.center,
              // color: Colors.red,
              child: Column(
                children: [
                accountLogicClogic.imageHeader.value==''?ClipOval(

                    child: Image.network(
                      accountLogicClogic.userJson['data'] == null
                          ? ''
                          : accountLogicClogic.userJson['data'][0]['image_128'],
                      fit: BoxFit.cover,
                      width: 50,
                      height: 50,
                    ),
                  ):ClipOval(
                  child: Image.file(File(accountLogicClogic.imageHeader.value), fit: BoxFit.cover,
                    width: 50,
                    height: 50,),
                ),
                  Container(
                    margin: EdgeInsets.only(top: 15),
                    alignment: Alignment.center,
                    // color: Colors.red,
                    width: 120,
                    child: Text(
                      accountLogicClogic.userJson['data'] == null
                          ? ''
                          : accountLogicClogic.userJson['data'][0]['name'],
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontWeight: FontWeight.w500,
                          color: HexColor('#333333'),
                          fontSize: 18),
                    ),
                  ),
                  GestureDetector(
                    child: Container(
                      margin: EdgeInsets.only(top: 5),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Image.asset(
                              accountLogicClogic.userJson['data'][0]['is_confirm'] == false
                                  ? A.assets_w1
                                  : A.assets_successRenzhen),
                          SizedBox(
                            width: 5,
                          ),
                          Text(
                            accountLogicClogic.userJson['data'][0]['is_confirm'] == false
                                ? '未实名认证'
                                : '已实名认证',
                            style: TextStyle(
                                fontSize: 12, color: HexColor('#999999')),
                          ),
                        ],
                      ),
                    ),
                    onTap: () {
                      if (accountLogicClogic.userJson['data'][0]['is_confirm'] == false) {
                        Get.to(RealNameAuthenPage());
                      } else {
                        Get.to(RenZhengInfoPage());
                      }
                    },
                  )
                ],
              )),
          GestureDetector(
            child: Container(
              height: 45,
              color: Colors.transparent,
              margin: EdgeInsets.only(top: 25, left: 25),
              // color: Colors.red,
              child: Container(
                child: Row(
                  children: [
                    Image.asset(A.assets_realnamerenzhen),
                    SizedBox(
                      width: 7,
                    ),
                    Text(
                      '实名认证',
                      style: TextStyle(
                          fontSize: 15, color: HexColor('#333333')),
                    )
                  ],
                ),
              ),
            ),
            onTap: () {
              print('实名认证');
              if (accountLogicClogic.userJson['data'][0]['is_confirm'] == false) {
                Get.to(RealNameAuthenPage());
              } else {
                Get.to(RenZhengInfoPage());
              }
            },
          ),
          GestureDetector(
            child: Container(
              color: Colors.transparent,
              height: 45,
              margin: EdgeInsets.only(top: 15, left: 25),
              // color: Colors.red,
              child: Container(
                child: Row(
                  children: [
                    Image.asset(A.assets_exs_cion),
                    SizedBox(
                      width: 7,
                    ),
                    Text(
                      '我的考试',
                      style: TextStyle(
                          fontSize: 15, color: HexColor('#333333')),
                    )
                  ],
                ),
              ),
            ),
            onTap: () {
              Get.to(MyExamsPages());
            },
          ),
          GestureDetector(
            onTap: () {
              Get.to(MyProfilePage());
            },
            child: Container(
              height: 45,
              color: Colors.transparent,
              margin: EdgeInsets.only(top: 15, left: 25),
              // color: Colors.red,
              child: Container(
                child: Row(
                  children: [
                    Image.asset(A.assets_kecheng_icon),
                    SizedBox(
                      width: 7,
                    ),
                    Text(
                      '我的收藏',
                      style: TextStyle(
                          fontSize: 15, color: HexColor('#333333')),
                    )
                  ],
                ),
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              Get.to(AccountSettingPage());
            },
            child: Container(
              color: Colors.transparent,
              height: 45,
              margin: EdgeInsets.only(top: 15, left: 25),
              // color: Colors.red,
              child: Container(
                child: Row(
                  children: [
                    Image.asset(A.assets_set_icon),
                    SizedBox(
                      width: 7,
                    ),
                    Text(
                      '账号设置',
                      style: TextStyle(
                          fontSize: 15, color: HexColor('#333333')),
                    )
                  ],
                ),
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              Get.to(HelpPages());
            },
            child: Container(
              height: 45,
              margin: EdgeInsets.only(top: 15, left: 25),
              color: Colors.transparent,
              child: Container(
                child: Row(
                  children: [
                    Image.asset(A.assets_help_icon),
                    SizedBox(
                      width: 7,
                    ),
                    Text(
                      '帮助中心',
                      style: TextStyle(
                          fontSize: 15, color: HexColor('#333333')),
                    )
                  ],
                ),
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              // Get.to(HelpPages());

              Get.to(MyWebView(title: '使用说明',url: 'https://docs.qq.com/s/BQ_PtGtdzuKjNqyOMMSD0a',));
            },
            child: Container(
              height: 45,
              margin: EdgeInsets.only(top: 15, left: 25),
              color: Colors.transparent,
              child: Container(
                child: Row(
                  children: [
                    Image.asset(A.assets_baise),
                    SizedBox(
                      width: 7,
                    ),
                    Text(
                      '使用说明',
                      style: TextStyle(
                          fontSize: 15, color: HexColor('#333333')),
                    )
                  ],
                ),
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              Get.dialog( AlertDialog(
                title: Text('提示?'),
                content: Text('确定要退出登录吗?'),
                actions: [
                  FlatButton(onPressed: (){
                    Get.offAll(LoginModulePage());
                  }, child: Text('确定')),
                  FlatButton(onPressed: (){
                    Get.back();
                  }, child: Text('取消'))
                ],
                elevation: 25,
              ));

            },
            child: Container(
              alignment: Alignment.center,
              margin:
              EdgeInsets.only(left: 15, right: 15, bottom: 0, top: 50),
              height: 35,
              child: Text('退出登录',
                  style: TextStyle(
                    fontSize: 14,
                    color: HexColor('#333333'),
                  )),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(4.0),
                border: Border.all(
                  color: HexColor('#DDDDDD'),
                  width: 1,
                ),
              ),
            ),
          )
        ],
      ),
    );

    // return GetBuilder(
    //   init: AccountLogic(),
    //   builder: (_) {
    //
    //   },
    // );
  }

  @override
  void dispose() {
    // Get.delete<HomeModuleLogic>();
    super.dispose();
  }
}

///  倒计时 class
class CountTextWidget extends StatefulWidget {
  var minutes = 0;

  int exam_seconds;

  CountTextWidget(this.exam_seconds);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return CountTextWidgetState();
  }
}

class CountTextWidgetState extends State<CountTextWidget> {
  final HomeModuleLogic logic = Get.put(HomeModuleLogic());

  // int seconds1 = 10;

  // Timer _timer;

//   void cancelTimer() {
//     if (_timer != null) {
//       _timer.cancel();
//       _timer = null;
//     }
//   }
//
//   void startTimer() {
//     //设置 1 秒回调一次
//     const period = const Duration(seconds: 1);
//     _timer = Timer.periodic(period, (timer) {
//       //更新界面
//       setState(() {
//         //秒数减一，因为一秒回调一次
//         logic.daoshiji.value--;
// //        print('我在更新界面>>>>>>>>>>>>>> $seconds');
// //         countContent = constructTime(seconds);
//       });
//       if ( logic.daoshiji.value == 0) {
//         //倒计时秒数为0，取消定时器
//
//         logic.requestDataWithXuzhi();
//
//
//         print('我被取消了  ');
//         BotToast.showText(text: '考试时间到');
//         cancelTimer();
//         // Get.off(ExamsCompletePage());
//         // getData();
//       }
//     });
//   }

  @override
  void dispose() {
    // cancelTimer();

    logic.cancelTimer();
    super.dispose();
  }

  // @override
  // void didChangeDependencies() {
  //   // TODO: implement didChangeDependencies
  //   super.didChangeDependencies();
  //   startTimer();
  // }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    logic.startTimer();

    print('++++++++++++++ ${widget.exam_seconds}');

    // print(widget.model.data[0].seconds);
    // print(widget.model.data[0].state);
    // String i = widget.exam_seconds;

    // var i1 = int.parse(i);

    // if(widget.exam_seconds<=0){
    //   seconds1 = 0;
    // }else{
    //   seconds1 = widget.exam_seconds;
    // }

    // logic.daoshiji.value = widget.exam_seconds;

    // startTimer();
  }

  //时间格式化，根据总秒数转换为对应的 hh:mm:ss 格式
  static String constructTime(int seconds) {
    int day = seconds ~/ 3600 ~/ 24;
    int hour = seconds ~/ 3600;
    int minute = seconds % 3600 ~/ 60;
    int second = seconds % 60;
    // if (day != 0) {
    //   return '$day天$hour小时$minute分$second秒后自动取消';
    // } else if (hour != 0) {
    //   return '$hour小时$minute分$second秒后自动取消';
    // } else if (minute != 0) {
    //   return '$minute分$second秒后自动取消';
    // } else if (second != 0) {
    //   return '$second秒后自动取消';
    // }
    // else {
    //   return '';
    // }
    return formatTime(hour) +
        ":" +
        formatTime(minute) +
        ":" +
        formatTime(second) +
        '';
  }

  //数字格式化，将 0~9 的时间转换为 00~09
  static String formatTime(int timeNum) {
    return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.exam_seconds <= 0 && widget.exam_seconds > -600) {
      return GestureDetector(
        onTap: () {
          Get.to(TextInstructionsPage('ksty'));
        },
        child: Container(
          child: Image.asset(A.assets_ksks),
        ),
      );
    } else if (widget.exam_seconds < -600) {
      return Container(
        child: Image.asset(A.assets_wfks),
      );
    }

    return Obx(() {
      return Text(
        '${constructTime(logic.daoshiji.value)}',
        style: TextStyle(
            fontSize: 32,
            color: HexColor('#333333'),
            fontWeight: FontWeight.w500),
      );
    });

    // TODO: implement build
    // return widget.exam_seconds==0||widget.exam_seconds>-600?Container(
    //   child: Image.asset(A.assets_ksks),
    //
    // ):Text(
    //   '${constructTime(widget.exam_seconds)}',
    //   style: TextStyle(
    //       fontSize: 32,
    //       color: HexColor('#333333'),
    //       fontWeight: FontWeight.w500),
    // );
  }



}



class DocumentModel {
  int folderId;
  String search;
  List<Data> data;
  int searchCount;
  int errcode;
  String errmsg;
  String message;

  DocumentModel(
      {this.folderId,
      this.search,
      this.data,
      this.searchCount,
      this.errcode,
      this.errmsg,
      this.message});

  DocumentModel.fromJson(Map<String, dynamic> json) {
    folderId = json['folder_id'];
    search = json['search'];
    if (json['data'] != null) {
      data = new List<Data>();
      json['data'].forEach((v) {
        data.add(new Data.fromJson(v));
      });
    }
    searchCount = json['search_count'];
    errcode = json['errcode'];
    errmsg = json['errmsg'];
    message = json['message'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['folder_id'] = this.folderId;
    data['search'] = this.search;
    if (this.data != null) {
      data['data'] = this.data.map((v) => v.toJson()).toList();
    }
    data['search_count'] = this.searchCount;
    data['errcode'] = this.errcode;
    data['errmsg'] = this.errmsg;
    data['message'] = this.message;
    return data;
  }
}

class Data {
  int id;
  String icon;
  String createDate;
  String writeDate;
  String pastTime;
  String name;
  String url;
  String mimetype;
  int folderId;
  String folderIdName;
  String type;
  String previewUrl;
  var download_url;
  var web_download_url;

  Data(
      {this.id,
      this.icon,
      this.createDate,
      this.writeDate,
      this.pastTime,
      this.name,
      this.url,
      this.mimetype,
      this.folderId,
      this.folderIdName,
      this.type,
        this.download_url,
        this.web_download_url,
      this.previewUrl});

  Data.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    icon = json['icon'];
    createDate = json['create_date'];
    writeDate = json['write_date'];
    pastTime = json['past_time'];
    name = json['name'];
    url = json['url'];
    mimetype = json['mimetype'];
    folderId = json['folder_id'];
    folderIdName = json['folder_id_name'];
    type = json['type'];
    previewUrl = json['preview_url'];
    download_url = json['download_url'];
     web_download_url = json['web_download_url'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['icon'] = this.icon;
    data['create_date'] = this.createDate;
    data['write_date'] = this.writeDate;
    data['past_time'] = this.pastTime;
    data['name'] = this.name;
    data['url'] = this.url;
    data['mimetype'] = this.mimetype;
    data['folder_id'] = this.folderId;
    data['folder_id_name'] = this.folderIdName;
    data['type'] = this.type;
    data['preview_url'] = this.previewUrl;
    return data;
  }
}
